package com.cmccgz.udacs_landlord_webapp.main.accreditmanager;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.baselibrary.view.DatePickerDialog;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.adapter.BindCardAdapter;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.CardInfo;
import com.cmccgz.udacs_landlord_webapp.bean.Person;
import com.cmccgz.udacs_landlord_webapp.interfaces.OnRvItemClickListenter;
import com.cmccgz.udacs_landlord_webapp.main.housemanager.list.HouseListActivity;
import com.cmccgz.udacs_landlord_webapp.update.StringUtils;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


/**
 * 开卡授权页面
 */
public class AccreditMngActivity extends BaseActivity implements AccreditMngContract.View, View.OnClickListener, OnRvItemClickListenter<CardInfo> {


    public static final String TAG = "AccreditMngActivity";
    public static final int CODE_SEL_HOUSE = 0x01;
    public static final int CODE_ADDCARD = 0X02;
    public static final int CODE_SEL_PERSON = 0X03;
    public static final int CODE_SEL_HOUSE_FOR_PERSEON = 0x04;
    private AccreditMngContract.Presenter mPresenter;
    private ViewHelper mViewHelper;

    private EditText et_house;
    private EditText et_endtime;
    private EditText et_username;
    private EditText et_credit;
    private CheckBox cb_opendoor;
    private Person person;
    private RecyclerView rv_cards;
    private List<CardInfo>cards=new ArrayList<>();
    private BindCardAdapter adapter;
    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected int setLayoutId() {
        return R.layout.activity_accredit_mng;
    }

    @Override
    protected void beforePermission() {
        mViewHelper = ViewHelper.instance(mContext);
        if (mViewHelper != null) {
            mViewHelper.setTitle("授权管理");
            mViewHelper.setAllVisable(false);
            mViewHelper.setBackTextVisable(true);
        }
    }

    @Override
    protected void initView() {
        mPresenter = new AccreditMngPresenter(this);

        LinearLayout content = (LinearLayout) findViewById(R.id.contentFrame);
        et_username = (EditText) findViewById(R.id.et_username);
        et_house = (EditText) findViewById(R.id.et_house);
        et_endtime = (EditText) findViewById(R.id.et_endtime);
        et_credit = (EditText) findViewById(R.id.et_credit);
        cb_opendoor = (CheckBox) findViewById(R.id.cb_opendoor);
        Button btn_complete = (Button) findViewById(R.id.btn_complete);
        rv_cards = ((RecyclerView) findViewById(R.id.rv_cards));

        //设置rv
/*        cards.add(new CardInfo("1","1","45464646541646546"));
        cards.add(new CardInfo("2","1","21231556243155656"));
        cards.add(new CardInfo("3","1","24125778906243444"));
        cards.add(new CardInfo("4","1","21341234124123414"));*/
        adapter = new BindCardAdapter(mContext,cards,this);
        rv_cards.setAdapter(adapter);
        rv_cards.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));

        //设置不可编辑
        et_house.setKeyListener(null);
        et_credit.setKeyListener(null);
        et_username.setKeyListener(null);
        et_endtime.setKeyListener(null);

        //设置点击监听
        et_house.setOnClickListener(this);
        et_username.setOnClickListener(this);
        et_credit.setOnClickListener(this);
        et_endtime.setOnClickListener(this);
        btn_complete.setOnClickListener(this);
        mViewHelper.setTitleOnClicklistener(this);
        mPresenter.start();
    }

    @Override
    protected void initFragment() {

    }


    @Override
    protected int setSystemBarColorId() {
        return 0;
    }

    @Override
    public void setPresenter(AccreditMngContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showEmptyHouse() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_house_tip);
    }

    @Override
    public void showEmptyEndTime() {
        ToastUtils.show(mContext, R.string.activity_cardaccredit_endtime_tip);
    }

    @Override
    public void showEmptyUserId(){
        ToastUtils.show(mContext, R.string.activity_cardaccredit_nouser_tip);
    }

    @Override
    public void showLoadingDialog() {
        showLoadingDialog("正在授权，请稍后...");
    }

    @Override
    public void hideLoadingDialog() {
        dismissLoadingDialog();
    }

    @Override
    public void appAccreditCardSuccess() {
        dismissLoadingDialog();
        showToast(R.string.activity_cardaccredit_success);
        finish();
    }

    @Override
    public void appAccreditError(String errMsg) {
        dismissLoadingDialog();
        showToast(errMsg);
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        String houseId = getHouseId();
        String houseName = getHouseName();
        switch (v.getId()) {
            case R.id.et_endtime:
                hideSoftKeyboard(getCurrentFocus());
                DatePickerDialog.showDatePickerDialogWhitMinDate(mContext, getText(R.string.activity_cardaccredit_endtime_dialong_title).toString(), new Date().getTime(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        et_endtime.setText(String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_format).toString(), year, monthOfYear + 1, dayOfMonth));
                        String format = String.format(Locale.CHINA, getText(R.string.activity_cardaccredit_time_remote_format).toString(), year, monthOfYear + 1, dayOfMonth);
                        String entTimeMil= "";
                        try {
                            entTimeMil = sdf.parse(format).getTime()+"";
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        et_endtime.setTag(entTimeMil);
                    }
                });
                break;
            case R.id.et_house:
                hideSoftKeyboard(getCurrentFocus());
                intent = new Intent(mContext, HouseListActivity.class);
                intent.putExtra(HouseListActivity.TYPE, HouseListActivity.TYPE_SELECT_BUILDING);
                intent.putExtra(HouseListActivity.IS_FOR_SELECTED, true);
                startActivityForResult(intent, CODE_SEL_HOUSE);
                break;
            case R.id.et_username:
            case R.id.et_credit:
            /*    if (StringUtils.isEmpty(houseId)) {*/
                    hideSoftKeyboard(getCurrentFocus());
                    intent = new Intent(mContext, HouseListActivity.class);
                    intent.putExtra(HouseListActivity.TYPE, HouseListActivity.TYPE_SELECT_HOUSE);
                    intent.putExtra(HouseListActivity.IS_FOR_SELECTED, true);
                    startActivityForResult(intent, CODE_SEL_HOUSE_FOR_PERSEON);
              /*  }else{
                    intent = new Intent(this, PersonListActivity.class);
                    intent.putExtra(PersonListActivity.HOUSE_ID, houseId);
                    intent.putExtra(PersonListActivity.HOUSE_NAME, houseName);
                    startActivityForResult(intent, CODE_SEL_PERSON);
                }*/
                break;
            case R.id.btn_complete:
                String mobile = AppConfig.getMobile(this);
                String endTime = et_endtime.getTag() == null ? "" : et_endtime.getTag().toString();
                String userId = person!=null?person.getUserMobile():"";
                String appOpen = cb_opendoor.isChecked()?"1":"0";
                mPresenter.completeAppAccredit(mobile,  houseId, endTime, userId, cards, appOpen);
                break;
            case R.id.tv_back:
                finish();
                break;
            default:
                break;
        }
    }

    @NonNull
    private String getHouseName() {
        return et_house.getText() == null ? "" : et_house.getText().toString();
    }

    private String getHouseId() {
        return et_house.getTag() == null ? "" : et_house.getTag().toString();
    }

    private void asyPersonInfo() {
        et_username.setText(person==null|| StringUtils.isEmpty(person.getUserName())?"":person.getUserName());
        et_credit.setText(person==null||StringUtils.isEmpty(person.getId_card())?"":person.getId_card());
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_SEL_HOUSE && resultCode == HouseListActivity.RESULT_CODE) {
            final String house_name = data.getStringExtra(HouseListActivity.HOUSE_NAME);
            final String house_id = data.getStringExtra(HouseListActivity.HOUSE_ID);
            if (cards!=null&&cards.size()>0
                    &&et_house.getTag()!=null
                    &&!et_house.getTag().equals(house_id)) {
                showConfirmDialog("提示", "当前房屋进行改变，修改后会清空已选卡片，是否继续修改？", "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        cards.clear();
                        adapter.notifyDataSetChanged();
                        et_house.setText(house_name);
                        et_house.setTag(house_id);
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                },false);
            }else{
                et_house.setText(house_name);
                et_house.setTag(house_id);
            }
        }
        if (requestCode == CODE_SEL_HOUSE_FOR_PERSEON && resultCode == HouseListActivity.RESULT_CODE) {
            String house_name = data.getStringExtra(HouseListActivity.HOUSE_NAME);
            String house_id = data.getStringExtra(HouseListActivity.HOUSE_ID);
            Intent intent = new Intent(this, PersonListActivity.class);
            intent.putExtra(PersonListActivity.HOUSE_ID, house_id);
            intent.putExtra(PersonListActivity.HOUSE_NAME, house_name);
            startActivityForResult(intent, CODE_SEL_PERSON);
        }
        if (requestCode==CODE_SEL_PERSON&&resultCode==RESULT_OK) {
            person = ((Person) data.getSerializableExtra(PersonListActivity.KEY_PERSON_RESULT));
            asyPersonInfo();
        }
        if(requestCode == CODE_ADDCARD&&resultCode==RESULT_OK){
            CardInfo cardinfo = (CardInfo) data.getSerializableExtra(AddCardActivity.KEY_CARD_RESULT);
            if (cardinfo!=null) {
                cards.add(cardinfo);
                adapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void onItemClick(CardInfo cardInfo, final int position, View itemView) {
        switch (adapter.getItemViewType(position)) {
            case -1:
                String houseId = getHouseId();
                if (StringUtils.isEmpty(houseId)) {
                    ToastUtils.show(mContext,"请选择房屋!");
                    return;
                }
                Intent intent = new Intent(this, AddCardActivity.class);
                intent.putExtra(PersonListActivity.HOUSE_ID, houseId);
                intent.putExtra(PersonListActivity.HOUSE_NAME, getHouseName());
                startActivityForResult(intent, CODE_ADDCARD);
                break;
            case 1:
                if (cardInfo==null) {
                    ToastUtils.show(mContext,"删除失败!");
                    return;
                }
                showConfirmDialog("提示", "确定删除卡号为:" + cardInfo.getCardNo() + "的卡片吗？", "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (position>=0&&position<cards.size()) {
                            cards.remove(position);
                            adapter.notifyDataSetChanged();
                            ToastUtils.show(mContext,"删除成功!");

                        }else{
                            ToastUtils.show(mContext,"删除失败!");
                        }
                        dialog.dismiss();
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                break;
        }
    }
}
